import request from "@/utils/request";
import { getToken } from "@/utils/auth";
const CHAT_BASE_URL = "/api/v1/chat";

const ChatAPI = {
  /**
   * 创建新会话
   * @returns 新会话ID
   */
  createSession() {
    return request<any, string>({
      url: `${CHAT_BASE_URL}/session`,
      method: "get",
    });
  },

  /**
   * 获取聊天历史记录
   * @param sessionId 会话ID
   * @returns 聊天消息列表
   */
  getHistory(sessionId: string) {
    return request<any, ChatMessageVO[]>({
      url: `${CHAT_BASE_URL}/history/${sessionId}`,
      method: "get",
    });
  },
  /**
   * 获取聊天历史记录
   * @param sessionId 会话ID
   * @returns 聊天消息列表
   */
  getArticleHistory(articleId: number) {
    return request<any, ChatMessageVO[]>({
      url: `${CHAT_BASE_URL}/history/article/${articleId}`,
      method: "get",
    });
  },

  /**
   * 发送消息（普通请求）
   * @param data 聊天请求参数
   * @returns 聊天响应
   */
  sendMessage(data: ChatRequest) {
    return request<any, ChatResponse>({
      url: `${CHAT_BASE_URL}`,
      method: "post",
      data: data,
    });
  },

  /**
   * 流式发送消息
   * @param data 聊天请求参数
   * @param onData 接收数据回调
   * @param onError 错误处理回调
   * @param signal 中止信号
   */
  async streamMessage(
    data: ChatRequest,
    onData: (chunk: string) => void,
    onError?: (error: Error) => void,
    signal?: AbortSignal
  ) {
    try {
      const accessToken = getToken(); // Get the token from your auth utility
      const response = await fetch(`/dev-api/${CHAT_BASE_URL}/stream`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: accessToken || "", // Add Authorization header
        },
        body: JSON.stringify(data),
        signal,
      });

      if (!response.ok) throw new Error("请求失败");

      const reader = response.body?.getReader();
      if (!reader) throw new Error("无法读取流");

      const decoder = new TextDecoder();
      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        const chunk = decoder.decode(value, { stream: true });
        onData(chunk);
      }
    } catch (error) {
      onError(error as Error);
    }
  },

  /**
   * 删除会话记录
   * @param sessionId 会话ID
   */
  deleteSession(sessionId: string) {
    return request({
      url: `${CHAT_BASE_URL}/${sessionId}`,
      method: "delete",
    });
  },
};

export default ChatAPI;

/** 聊天请求参数 */
export interface ChatRequest {
  /** 会话ID */
  articleId: number;
  /** 用户消息 */
  message: string;
  /** 可选参数 */
  options?: {
    /** 温度值 */
    temperature?: number;
    /** 最大令牌数 */
    maxTokens?: number;
  };
}

/** 聊天响应 */
export interface ChatResponse {
  /** 会话ID */
  articleId: number;
  /** AI回复内容 */
  content: string;
}

/** 聊天消息VO */
export interface ChatMessageVO {
  /** 消息ID */
  id: string;
  /** 文章ID */
  articleId: number;
  /** 角色 (user|assistant) */
  role: "user" | "assistant";
  /** 消息内容 */
  content: string;
  /** 创建时间 */
  createTime: string;
}
